import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import userApi from "@/api/userinfo";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  // 用户信息改了,所有涉及到获取用户信息的地方都需要改
  // 1. router.beforeEach 通过获取用户名判断登录
  // 2. 首页 hello, admin -> 用户名获取方式改变
  // 3. navBar 用户名和头像的展示
  state: (): UserInfoState => ({
    token: getToken() as string,
    menuRoutes: [],
    userInfo:{
      avatar:"",
      buttons:[],
      name:"",
      roles:[],
      routes:[]
    }
  }),

  actions: {
    async login(username: string, password: string) {

      try {
        const result = await userApi.login({ username, password });
        this.token = result.token;
        //将token存储到缓存当中
        setToken(result.token);
        console.log(setToken(result.token));
        ElMessage.success("登录成功");
        return "成功";
      } catch (error) {
        ElMessage.error("用户名或密码错误!");
        return Promise.reject(new Error("用户名或密码错误!"));
      }
    },

    async getInfo() {
      try {
        const result = await userApi.info();
        this.userInfo.name = result.name;
        this.userInfo.avatar = result.avatar;
        const menuResult = await userApi.menu();
        if (menuResult) {
          this.menuRoutes = staticRoutes;
        }
      } catch (error) {
        this.reset();
        console.log(Promise.reject(new Error("获取用户信息失败")));
        return "获取用户信息失败";
      }
    },

    async QuitLogout() {
      const result = await userApi.logout();
      if (result) {
        this.reset();
        ElMessage.info("退出登录成功");
      }

    },
    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.userInfo.name = "";
      this.userInfo.avatar = "";
    }
  }
});
